﻿using System;
using UnityEngine;

namespace Runtime.ADAggregator
{
    public sealed class AdTimeHandler
    {
        private float _maxTime;
        private float _delayTime;
        private Action _onComplete;
        private Action<float> _onUpdate;
        private GameObject _gameObject;
        private bool _isMono;
        private bool _isPause;

        public bool IsDone => this._delayTime >= this._maxTime;
        public bool IsPlaying => !IsDone && !this._isKill;

        internal bool _isKill;

        internal AdTimeHandler(float delay, Action callback, Action<float> onUpdate = null)
        {
            this._maxTime = delay;
            this._delayTime = 0;
            this._onComplete = callback;
            this._onUpdate = onUpdate;
            this._isMono = false;
            this._isKill = false;
        }

        internal AdTimeHandler(GameObject gameObject, float delay, Action callback, Action<float> onUpdate = null)
        {
            this._maxTime = delay;
            this._delayTime = 0;
            this._onComplete = callback;
            this._onUpdate = onUpdate;
            this._gameObject = gameObject;
            this._isMono = true;
            this._isKill = false;
        }

        internal void Update()
        {
            if (!this.IsDone)
            {
                if (this._isMono)
                {
                    if (System.Object.ReferenceEquals(this._gameObject, null))
                    {
                        this.Kill();
                    }
                }

                if (!this._isPause)
                {
                    this._onUpdate?.Invoke(this._delayTime / this._maxTime);
                    this._delayTime += Time.deltaTime;
                }

                if (this.IsDone)
                {
                    this._onComplete?.Invoke();
                    this.Kill();
                }
            }
        }

        public void Kill()
        {
            this._isKill = true;
        }

        public void Pause(bool b)
        {
            this._isPause = b;
        }
    }
}